package com.xcjh.interceptor;

import com.xcjh.base.dto.Result;
import com.xcjh.base.dto.Status;
import com.xcjh.utils.JsonUtil;
import com.xcjh.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 后端登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtils redisUtils;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        // 从请求头中获取token
        String token = request.getHeader("token");
        // 判断token是否为空
        if (!StringUtils.isEmpty(token)) {
            // redis获取token的值
            Object loginTemp = redisUtils.get(token);
            if (loginTemp != null) {// 如有有值
                // 刷新过期时间，重新定位到30分钟
                return true;
            }
        }else {
            return true;//TODO:: 如果有else true的话,那么所有接口不传token也能正常范围. 仅限于测试阶段. 上生产环境时禁止使用
        }
        // 前端没有传token或者时间过期
        // 设置响应数据类型和字符串
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        // 获取字符输出流
        PrintWriter writer = response.getWriter();
//        {"success":false,"message":"noLogin"}
        writeError(writer,!StringUtils.isEmpty(token));
        return false;
    }

    private void writeError(PrintWriter writer,boolean hasToken){
        writer.write(JsonUtil.getGson().toJson(Result.error(hasToken?Status.LOGIN_TIME_OUT:Status.NO_LOGIN)));
        writer.close();
    }

}
